import axios from 'axios'
import { trackEvent } from './analytics'

const service = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL,
    timeout: 15000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        // 添加token
        const token = localStorage.getItem('token')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }

        // 请求埋点
        trackEvent('api_request', {
            url: config.url,
            method: config.method,
            timestamp: new Date().getTime()
        })

        return config
    },
    error => {
        trackEvent('api_request_error', {
            error: error.message,
            timestamp: new Date().getTime()
        })
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        // 响应成功埋点
        trackEvent('api_response_success', {
            url: response.config.url,
            status: response.status,
            duration: new Date().getTime() - response.config.timestamp,
        })

        return response.data
    },
    error => {
        // 响应错误埋���
        trackEvent('api_response_error', {
            url: error.config?.url,
            status: error.response?.status,
            error: error.message,
            duration: new Date().getTime() - error.config?.timestamp,
        })

        return Promise.reject(error)
    }
)

export default service 